package com.zdzx.controller.web;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdzx.base.common.util.RedisUtil;
import com.zdzx.base.common.util.UserInfoUtil;
import com.zdzx.common.result.PageInfo;
import com.zdzx.common.result.PageUtil;
import com.zdzx.common.result.Result;
import com.zdzx.common.result.ResultCode;
import com.zdzx.common.result.ResultUtil;
import com.zdzx.mapper.CourseCollectionMapper;
import com.zdzx.mapper.CourseMapper;
import com.zdzx.mapper.CourseMessageMapper;
import com.zdzx.mapper.CourseTypeMapper;
import com.zdzx.mapper.CourseUserMapper;
import com.zdzx.mapper.CourseWatchMapper;
import com.zdzx.mapper.DicMapper;
import com.zdzx.mapper.SystemConfigMapper;
import com.zdzx.model.service.base.result.UserInfo;
import com.zdzx.model.service.base.vo.Dic;
import com.zdzx.model.service.base.vo.SystemConfig;
import com.zdzx.model.service.content.param.UserMessage;
import com.zdzx.model.service.content.result.CourseDetails;
import com.zdzx.model.service.content.result.CourseList;
import com.zdzx.model.service.content.result.CourseMessageList;
import com.zdzx.model.service.content.vo.Course;
import com.zdzx.model.service.content.vo.CourseCollection;
import com.zdzx.model.service.content.vo.CourseMessage;
import com.zdzx.model.service.content.vo.CourseType;
import com.zdzx.model.service.content.vo.CourseUser;
import com.zdzx.model.service.content.vo.CourseWatch;
import com.zdzx.service.OSSService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "web课程")
@RestController()
@RequestMapping("/web")
public class WebCourseController {
	

	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private CourseMapper courseMapper;
	@Autowired
	private CourseWatchMapper courseWatchMapper;
	@Autowired
	private CourseUserMapper courseUserMapper;
	@Autowired
	private CourseMessageMapper courseMessageMapper;
	@Autowired
	private CourseCollectionMapper courseCollectionMapper;
	@Autowired
	private CourseTypeMapper courseTypeMapper;
	@Autowired
	private OSSService ossService;
	@Autowired
	private SystemConfigMapper systemConfigMapper;
	//@Autowired
	//private HttpServletResponse response;
	@Autowired
	private DicMapper dicMapper;
	@ApiOperation(value = "课程/企业课程", notes = "")
	@GetMapping("/courseType")
	public Result<List<Dic>> courseType(
			@ApiParam("") @RequestParam(value = "tenantId", required = false) String tenantId
			) {
		QueryWrapper<Dic> queryWrapper=new QueryWrapper<Dic>();
		queryWrapper.eq("`parent_type`", "course_type");
		queryWrapper.orderByAsc("`index`");
		if(!StringUtils.isEmpty(tenantId)) {
			queryWrapper.eq("tenant_id", StringUtils.isEmpty(tenantId)?"00000000":tenantId);
		}
		List<Dic> list = dicMapper.selectList(queryWrapper);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),null, list);
	}
	
	@ApiOperation(value = "课程/企业课程", notes = "")
	@GetMapping("/courseType/systemConfig")
	public Result<List<SystemConfig>> courseTypeConfig() {
		QueryWrapper<SystemConfig> queryWrapper=new QueryWrapper<SystemConfig>();
		queryWrapper.in("`key`", Arrays.asList("OPEN_ARTICLE","OPEN_VIDEO"));
		List<SystemConfig> selectList = systemConfigMapper.selectList(queryWrapper);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),null, selectList);
	}
	
	
	@ApiOperation(value = "课程/企业课程", notes = "")
	@GetMapping("/course/da")
	public Result<PageInfo<CourseList>> course(
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			@ApiParam("") @RequestParam(value = "isPackage", required = false) String isPackage,
			@ApiParam("") @RequestParam(value = "title", required = false) String title,
			@ApiParam("") @RequestParam(value = "tenantId", required = false) String tenantId,
			@ApiParam("1免费 0收费") @RequestParam(value = "free", required = false) String free,
			@ApiParam("0视频 1文章 2直播") @RequestParam(value = "type", required = false) String type,
			@ApiParam("") @RequestParam(value = "courseType", required = false)String courseType,
			@ApiParam("") @RequestParam(value = "courseCategory", required = false)String courseCategory,
			@ApiParam("0热度 1浏览量") @RequestParam(value = "sort", required = false) String sort) {
		
		if(pageNum==null||pageSize==null) {
			pageNum=1;
			pageSize=10;
		}
		Page<Course> page = new Page<>(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
		QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
		if (!StringUtils.isEmpty(title)) {
			queryWrapper.like("title", title);
		}
		if (!StringUtils.isEmpty(tenantId)) {
			queryWrapper.eq("tenant_id", tenantId);
			if(StringUtils.isEmpty(isPackage))
				queryWrapper.eq("is_package", 1);
			else
				queryWrapper.eq("is_package", isPackage);
		}else {
			queryWrapper.eq("tenant_id", "00000000");
			queryWrapper.eq("is_package", 1);
		}
		if (!StringUtils.isEmpty(free)) {
			queryWrapper.eq("free", free);
		}
		if (!StringUtils.isEmpty(type)) {
			queryWrapper.eq("type", type);
		}
		if (!StringUtils.isEmpty(courseCategory)) {
			queryWrapper.eq("category", courseCategory);
		}
		
		if(!StringUtils.isEmpty(sort)&&sort.equals("1")) {
			queryWrapper.orderByDesc("views");
		}else {
			queryWrapper.orderByDesc("create_time");
		}
		
		queryWrapper.select("id", "title", "lecturer", "price", "free", "title_image","data_image","type","create_time", "views","path");
		//queryWrapper.eq("parent_id", "0");
		IPage<CourseType> selectPage=null;
		if (!StringUtils.isEmpty(courseType)) {
			Page<CourseType> page1 = new Page<>(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
			QueryWrapper<CourseType> queryWrapper1=new QueryWrapper<CourseType>();
			List<String> ctype=new ArrayList<String>();
			if(courseType.contains(",")) {
				String[] split = courseType.split(",");
				for (String string : split) {
					ctype.add(string);
				}
			}else {
				ctype.add(courseType );
			}
			queryWrapper1.groupBy("course_id");
			
			selectPage = courseTypeMapper.selectPageByType(page1,ctype,ctype.size(),tenantId);
			List<String> ids=new ArrayList<String>();
			for(CourseType t : selectPage.getRecords()) {
				ids.add(t.getCourseId());
			}
			if(ids.size()==0)
				ids.add("0");
			queryWrapper.in("id", ids);
		}
		
		IPage<Course> info = courseMapper.selectPage(page, queryWrapper);
		List<CourseList> resultList = new ArrayList<CourseList>();
		if (info.getRecords().size() > 0) {
			for (Course course : info.getRecords()) {
				CourseList temp = new CourseList();
				BeanUtils.copyProperties(course, temp);
				resultList.add(temp);
			}
		}
		PageInfo<CourseList> data = PageUtil.data(StringUtils.isEmpty(courseType)?info.getPages():selectPage.getPages(),
				StringUtils.isEmpty(courseType)?info.getCurrent():selectPage.getCurrent(), StringUtils.isEmpty(courseType)?info.getTotal():selectPage.getTotal()
						, resultList);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, data);
	}
	
	
	
	
	
	@ApiOperation(value = "课程/企业课程", notes = "")
	@GetMapping("/course")
	public Result<PageInfo<CourseList>> courseda(
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			@ApiParam("") @RequestParam(value = "isPackage", required = false) String isPackage,
			@ApiParam("") @RequestParam(value = "title", required = false) String title,
			@ApiParam("") @RequestParam(value = "tenantId", required = false) String tenantId,
			@ApiParam("1免费 0收费") @RequestParam(value = "free", required = false) String free,
			@ApiParam("0视频 1文章 2直播") @RequestParam(value = "type", required = false) String type,
			@ApiParam("") @RequestParam(value = "courseType", required = false)String courseType,
			@ApiParam("") @RequestParam(value = "courseCategory", required = false)String courseCategory,
			@ApiParam("0热度 1浏览量") @RequestParam(value = "sort", required = false) String sort) {
		
		if(pageNum==null||pageSize==null) {
			pageNum=1;
			pageSize=10;
		}
		Page<Course> page = new Page<>(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
		QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
		if (!StringUtils.isEmpty(title)) {
			queryWrapper.like("title", title);
		}
		if (!StringUtils.isEmpty(tenantId)) {
			queryWrapper.eq("tenant_id", tenantId);
			if(StringUtils.isEmpty(isPackage))
				queryWrapper.eq("is_package", 1);
			else
				queryWrapper.eq("is_package", isPackage);
		}else {
			queryWrapper.eq("tenant_id", "00000000");
			queryWrapper.eq("is_package", 1);
		}
		if (!StringUtils.isEmpty(free)) {
			queryWrapper.eq("free", free);
		}
		if (!StringUtils.isEmpty(type)) {
			queryWrapper.eq("type", type);
		}
		if (!StringUtils.isEmpty(courseType)) {
			queryWrapper.eq("course_type", courseType);
		}
		if (!StringUtils.isEmpty(courseCategory)) {
			queryWrapper.eq("category", courseCategory);
		}
		
		if(!StringUtils.isEmpty(sort)&&sort.equals("1")) {
			queryWrapper.orderByDesc("views");
		}else {
			queryWrapper.orderByDesc("create_time");
		}
		
		queryWrapper.select("id", "title", "lecturer", "price", "free", "title_image","data_image","type","create_time", "views","path");
		queryWrapper.eq("parent_id", "0");
		
		IPage<Course> info = courseMapper.selectPage(page, queryWrapper);
		List<CourseList> resultList = new ArrayList<CourseList>();
		if (info.getRecords().size() > 0) {
			for (Course course : info.getRecords()) {
				CourseList temp = new CourseList();
				BeanUtils.copyProperties(course, temp);
				resultList.add(temp);
			}
		}
		PageInfo<CourseList> data = PageUtil.data(info.getPages(),
				info.getCurrent(), info.getTotal()
						, resultList);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, data);
	}
	
	
	
	
	@ApiOperation(value = "课程详情", notes = "")
	@GetMapping("/course/{courseId}")
	public Result<CourseDetails> course(@PathVariable("courseId")String courseId,HttpServletRequest request) {
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		//总课数： 8 播放次数： 818次 学习人数：7882人
		CourseDetails courseDetails=new CourseDetails();
		QueryWrapper<Course> queryWrapper = new QueryWrapper<Course>();
		queryWrapper.eq("id", courseId);
		queryWrapper.eq("parent_id", "0");
		List<Course> courses = courseMapper.selectList(queryWrapper);
		if(courses!=null&&courses.size()>0) {
		String ip = "";
		if(request.getHeader("x-forwarded-for") == null) {
			ip = request.getRemoteAddr();
		}else{
			ip = request.getHeader("x-forwarded-for");
		}
		courseDetails.setFree(courses.get(0).getFree());
		String views = (String)redisUtil.get(courseId+":"+ip);
		if(StringUtils.isEmpty(views)&&courses!=null&&courses.size()>0) {
			redisUtil.set(courseId+":"+ip,"0",getMiao());
			Course entity=new Course();
			entity.setId(courseId);
			entity.setViews((courses.get(0).getViews()==null?0:courses.get(0).getViews())+1);
			courseMapper.updateById(entity);
			
		}
		//学习人数
		QueryWrapper<CourseWatch> queryWrapperWatch=new QueryWrapper<CourseWatch>();
		queryWrapperWatch.select("DISTINCT user_id");
		queryWrapperWatch.eq("course_parent_id", courseId);
		List<CourseWatch> studyList = courseWatchMapper.selectList(queryWrapperWatch);
		Course course = courses.get(0);
		BeanUtils.copyProperties(course, courseDetails);
		if(studyList!=null&&studyList.size()>0)
		courseDetails.setStudyCount(studyList.size());
		
		
		//总课时
		QueryWrapper<Course> queryWrapperCount=new QueryWrapper<Course>();
		queryWrapper.select("id");
		queryWrapperCount.eq("parent_id", courseId);
		List<Course> count = courseMapper.selectList(queryWrapperCount);
		courseDetails.setCourseCount(count==null?0:count.size());
		//用户是否购买
		if("0".equals(courseDetails.getFree())&&loginInfo!=null) {
			if("1".equals(loginInfo.getIsVip())) {
				courseDetails.setP(0);
			}else {
				QueryWrapper<CourseUser> queryWrapperUser =new QueryWrapper<CourseUser>();
				queryWrapperUser.eq("user_id", loginInfo.getId());
				queryWrapperUser.eq("course_id", courseId);
				List<CourseUser> selectList = courseUserMapper.selectList(queryWrapperUser);
				if(selectList!=null&&selectList.size()>0) {
					CourseUser courseUser = selectList.get(0);
					if(courseUser.getExpireTime().isAfter(LocalDateTime.now())){
						courseDetails.setP(0);
					}
				}
			}
			
			String tenantId = loginInfo.getTenantId();
			if(!courseDetails.getTenantId().equals("00000000")&&!StringUtils.isEmpty(tenantId)) {
				if(loginInfo.getTenantId().equals(courseDetails.getTenantId()))
					courseDetails.setP(0);
			}
			
		}
		
		if(loginInfo!=null) {
			QueryWrapper<CourseCollection> queryWrapperCollection=new QueryWrapper<CourseCollection>();
			queryWrapperCollection.eq("user_id", loginInfo.getId());
			queryWrapperCollection.eq("course_id", courseId);
			List<CourseCollection> collect = courseCollectionMapper.selectList(queryWrapperCollection);
			if(collect!=null&&collect.size()>0) {
				courseDetails.setCollection("1");
			}
		}
		}
		
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null,courseDetails);
	}
	
	@ApiOperation(value = "获取课程全部视频", notes = "")
	@GetMapping("/course/list/{courseId}")
	public Result<List<Course>> courseList(@PathVariable("courseId")String courseId,HttpServletRequest request){
		Course course = courseMapper.selectById(courseId);
		if (course == null) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "课程不存在！！！", null);
		}
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if (loginInfo == null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
		}
		
		if(!course.getTenantId().equals("00000000")) {
			/*if(!course.getTenantId().equals(loginInfo.getTenantId())) {
				return ResultUtil.data(ResultCode.NOT_BUY_COURSE.getCode(), ResultCode.NOT_BUY_COURSE.getMes(),null);
			}*/
		}else {
			if ("0".equals(course.getFree())) {
			if ("0".equals(loginInfo.getIsVip())) {
				QueryWrapper<CourseUser> queryWrapper = new QueryWrapper<>();
				queryWrapper.eq("user_id", loginInfo.getId());
				queryWrapper.eq("course_id", courseId);
				List<CourseUser> courseUsers = courseUserMapper.selectList(queryWrapper);
				if (courseUsers == null || courseUsers.size() == 0) {
					return ResultUtil.data(ResultCode.NOT_BUY_COURSE.getCode(), ResultCode.NOT_BUY_COURSE.getMes(),
							null);
				}else if (courseUsers.get(0).getExpireTime().isBefore(LocalDateTime.now())) {
					courseUserMapper.selectById(courseUsers.get(0).getId());
					return ResultUtil.data(ResultCode.BUY_COURSE_EXPIRE.getCode(),
							ResultCode.BUY_COURSE_EXPIRE.getMes(), null);
				}
			}
		}
		}
		QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("parent_id", courseId);
		queryWrapper.orderByAsc("sort");
		List<Course> list = courseMapper.selectList(queryWrapper);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, list);
	}
	
	@ApiOperation(value = "课程讨论", notes = "")
	@PostMapping("/course/message")
	public Result<String> detailsMessage(@RequestBody UserMessage userMessage,HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if(loginInfo==null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(),ResultCode.NOT_LOGIN.getMes() , null);
		}
		QueryWrapper<Course> queryWrapper = new QueryWrapper<Course>();
		queryWrapper.eq("id", userMessage.getCourseId());
		queryWrapper.eq("parent_id", "0");
		List<Course> courses = courseMapper.selectList(queryWrapper);
		if (courses == null || courses.size() == 0) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "课程ID不存在", null);
		}
		
		CourseMessage courseMessage = new CourseMessage();
		courseMessage.setCreateTime(LocalDateTime.now());
		courseMessage.setCourseId(userMessage.getCourseId());
		courseMessage.setUserId(loginInfo.getId());
		courseMessage.setContent(userMessage.getContent());
		courseMessage.setUsername(loginInfo.getAccount());
		int insert = courseMessageMapper.insert(courseMessage);
		return ResultUtil.data(insert > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(),
				null, null);
	}
	
	@ApiOperation(value = "课程讨论列表", notes = "")
	@GetMapping("/course/message/{courseId}")
	public Result<PageInfo<CourseMessageList>> getDetailsMessage(@PathVariable("courseId") String courseId,
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize){
		if(pageNum==null||pageSize==null) {
			pageNum=1;
			pageSize=10;
		}
		Page<CourseMessage> page = new Page<>(pageNum==null?1:pageNum, pageSize==null?10:pageSize);
		QueryWrapper<CourseMessage> queryWrapper = new QueryWrapper<CourseMessage>();
		queryWrapper.eq("course_id", courseId);
		queryWrapper.orderByDesc("create_time");
		IPage<CourseMessageList> info = courseMessageMapper.selectUserMessagePage(page, courseId);
		PageInfo<CourseMessageList> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(),
				info.getRecords());
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, data);
	}
	
	@ApiOperation(value = "获取收费课程播放地址", notes = "")
	@GetMapping("/course/checked/{courseId}")
	public Result<String> getCourseUrl(@PathVariable("courseId") String courseId,HttpServletRequest request) throws IOException{
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if(loginInfo==null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(),ResultCode.NOT_LOGIN.getMes() , null);
		}
		Result<String> checkedHas = checkedHas(courseId,request);
		if(ResultCode.RESULT_SUCCESS.getCode().equals(checkedHas.getCode())) {
			String data = checkedHas.getData();
			String newData = data.replace(com.zdzx.model.constant.SystemConfig.ossIp, "");
			String bucketName=newData.substring(0, newData.indexOf("/"));
			String objectName=newData.replace(bucketName, "");
			Result<String> url = ossService.getUrl(bucketName, objectName);
			return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, url.getData());
		}else {
			return checkedHas;
		}
	}
	
	
	@ApiOperation(value = "获取收费课程视频", notes = "")
	@GetMapping("/course/rescoure/{courseId}")
	public void getCourseRescoure(@PathVariable("courseId") String courseId,HttpServletRequest request,HttpServletResponse response) throws IOException{
		    Course selectById = courseMapper.selectById(courseId);
			if(selectById!=null) {
				String replace = selectById.getPath().replace("https://cnzdzx.com/resouce/", "");
				int indexOf = replace.indexOf("/");
				String s = replace.substring(0, indexOf);
				String e = replace.substring(indexOf);
				InputStream downFile = ossService.downFile(s, e);
				response.setHeader("Content-Type", "video/mp4");
				response.setHeader("Content-Length", "31274326");
				IOUtils.copy(downFile, response.getOutputStream());
				response.flushBuffer();
			}else {
				response.sendError(500);
			}
	}
	
	@ApiOperation(value = "记录课程学习时长", notes = "")
	@PostMapping("/course/watch/{courseId}/{countTime}")
	public Result<String> setCourseWatch(@PathVariable("courseId") String courseId,
			@PathVariable("countTime")int countTime,HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if (loginInfo == null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
		}
		//QueryWrapper<Course> queryWrapperCourse = new QueryWrapper<Course>();
		//queryWrapperCourse.eq("course_id", courseId);
		//queryWrapperCourse.eq("user_id", loginInfo.getId());
		Course course = courseMapper.selectById(courseId);
		if (course == null) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "该章节找不到！！！", null);
		}

		QueryWrapper<CourseWatch> queryWrapper = new QueryWrapper<CourseWatch>();
		queryWrapper.eq("course_id", courseId);
		queryWrapper.eq("user_id", loginInfo.getId());
		List<CourseWatch> watchs = courseWatchMapper.selectList(queryWrapper);
		int i = 0;
		if (watchs == null || watchs.size() == 0) {
			CourseWatch entity = new CourseWatch();
			entity.setCountTime(countTime);
			entity.setCourseId(courseId);
			entity.setUserId(loginInfo.getId());
			entity.setCreateTime(LocalDateTime.now());
			entity.setUpdateTime(LocalDateTime.now());
			entity.setCourseParentId("0".equals(course.getParentId())?courseId:course.getParentId());
			i = courseWatchMapper.insert(entity);
		} else {
			CourseWatch courseWatch = watchs.get(0);
			courseWatch.setUpdateTime(LocalDateTime.now());
			courseWatch.setCountTime(courseWatch.getCountTime() + countTime);
			i = courseWatchMapper.updateById(courseWatch);
		}

		return ResultUtil.data(i > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null,
				null);
	}
	
	
	
	
	
	public  Result<String> checkedHas(String courseId, HttpServletRequest request) {
		Course course = courseMapper.selectById(courseId);
		if (course == null) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "章节不存在！！！", null);
		}
		Course parent=null;
		if(StringUtils.isEmpty(course.getPath())) {
			parent = courseMapper.selectById(course.getParentId());
			if (parent == null) {
				return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "课程不存在！！！", null);
			}
		}else {
			parent=course;
		}
		
		if ("0".equals(parent.getFree())) {
			UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
			if (loginInfo == null) {
				return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
			}
			if(parent.getTenantId().equals(loginInfo.getTenantId())) {
				return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, course.getPath());
			}
			if ("0".equals(loginInfo.getIsVip())) {
				QueryWrapper<CourseUser> queryWrapper = new QueryWrapper<>();
				queryWrapper.eq("user_id", loginInfo.getId());
				queryWrapper.eq("course_id", parent.getId());
				List<CourseUser> courseUsers = courseUserMapper.selectList(queryWrapper);
				if (courseUsers == null || courseUsers.size() == 0) {
					return ResultUtil.data(ResultCode.NOT_BUY_COURSE.getCode(), ResultCode.NOT_BUY_COURSE.getMes(),
							null);
				} else if (courseUsers.get(0).getExpireTime().isBefore(LocalDateTime.now())) {
					courseUserMapper.selectById(courseUsers.get(0).getId());
					return ResultUtil.data(ResultCode.BUY_COURSE_EXPIRE.getCode(),
							ResultCode.BUY_COURSE_EXPIRE.getMes(), null);
				}
			}
		}
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, course.getPath());
	}
	public static int getMiao(){
		//long milliSecondsLeftToday = 86400000 - DateUtils.getFragmentInMilliseconds(Calendar.getInstance(), Calendar.DATE);
        long secondsLeftToday = 86400 - DateUtils.getFragmentInSeconds(Calendar.getInstance(), Calendar.DATE);
        return (int)secondsLeftToday;
	}
	public static void main(String[] args) {
		//OssUtil.upload("undefined", "20201103/course/c51eb8d9-59ad-4dbe-9f17-d7bde1c3936f.mp4", file)
	}
}
